<template>
	<view class="big-box">
		<view class="box">
			<view class="box-header-all">
				<img :src="fanhuitu" @click="fanhui" alt="返回" class="fanhui" />
				<view class="box-header">职业锚测试</view>
				<!-- 底部按钮 -->
				<view class="footer">
					<view class="footer-content">
						<text class="auto-next-text">点击查看题号</text>
						<img :src="liebiao" class="liebiao" @click="toggleQuestionList"></img>
					</view>
				</view>
			</view>
		</view>
		<view class="box2">
			<view class="div2">
				<view class="question-progress">
					{{p}}<text class="question-total"> /{{Data.total}}</text>
				</view>
				<view class="div3">
					<view class="auto-next-text">自动跳转下一题</view>
					<u-switch size="25" v-model="value"></u-switch>
				</view>
			</view>

			<view class="div4">
				<view class="question-text">{{Data.rows[id].questionText}}</view>
				<view class="options-box">
					<view class="option-item1" :class="{ selected: selectedOptions[id] === 3 }" @click="select(3)">A.
						非常符合</view>
					<view class="option-item1" :class="{ selected: selectedOptions[id] === 2 }" @click="select(2)">B.
						符合</view>
					<view class="option-item1" :class="{ selected: selectedOptions[id] === 1 }" @click="select(1)">C.
						不符合</view>
					<view class="option-item1" :class="{ selected: selectedOptions[id] === 0 }" @click="select(0)">D.
						非常不符</view>
				</view>
			</view>

			<view class="div6" @click="unclick(2)" v-show="id>0">
				<img :src="jiantou" class="jiantou" />
				<text class="prev-text">上一题</text>
			</view>
			<view class="btn-box">
				<button class="button1" @click="unclick(1)">{{text}}</button>
				<button class="button2" @click="checkAndSubmit">提交</button>
			</view>
		</view>

		<view class="question-nav-container">
			<scroll-view scroll-x class="question-nav-scroll" :scroll-with-animation="true" :scroll-left="scrollLeft"
				style="scroll-behavior: smooth;  width: 96vw; margin: 0 2vw;">
				<view class="question-nav-list">
					<view v-for="(item, index) in Data.rows" :key="index" class="question-item" :class="{
								'answered': selectedOptions[index] !== undefined,
								'current': index === id
							}" @click="jumpToQuestion(index)">
						{{ index + 1 }}
					</view>
				</view>
			</scroll-view>
		</view>
		<!-- 弹窗组件（简化版） -->
		<view v-if="showAllQuestionsModal" class="modal-overlay" @click.self="toggleQuestionList">
			<view class="modal-content">
				<view class="modal-header">
					<text>题号列表:</text>
				</view>
				<view v-if="Data.rows && Data.rows.length > 0" class="question-list">
					<template v-for="(item, index) in Data.rows">
						<view class="question-number" :key="item.id" :class="{
						      'answered': selectedOptions[index] !== undefined,
						      'current': index === id
						    }" @tap="jumpToQuestion(index)" @click="jumpToQuestion(index)">
							{{ index + 1 }}
						</view>
					</template>
				</view>
			</view>
		</view>
	</view>
</template>
<script>
	import {
		getCareeranchorTest
	} from '@/api/mentalTest/CareerAnchorTest.js';
	export default {
		data() {
			return {
				fanhuitu: this.$baseURL + '/profile/upload/2025/06/07/fanhui_20250607171430A035.png',
				showAllQuestionsModal: false, // 控制是否显示弹窗
				scrollQueue: [], // 滚动任务队列
				isScrolling: false, // 当前是否有滚动任务正在进行
				scrollLeft: 0, // 控制滚动位置
				jiantou: this.$baseURL + '/profile/upload/2025/05/28/jiantou_20250528162511A011.png',
				liebiao: this.$baseURL + '/profile/upload/2025/05/28/liebiao_20250528163750A012.png',
				selectedOptions: {},
				id: 0,
				p: 1,
				text: "下一题",
				ResultMap: null,
				value: true,
				answerMap: {}, // 新增：用于记录每题是否已答
				startingTime: 0, // 记录当前时间
				endingTime: 0, // 记录结束时间
				startDate: null,
				duringTime: 0,
				isSubmit: true,
				testId: null,
				dateResult: {
					type: null,
					startTime: "",
					during: "",
					address: "秦皇岛市",
					nickName: "张三",
					aiText: ""
				},
				storageData: {},

				Data: {
					rows: [],
					total: 0
				},
				mbtiStatus: { // mbti测试状态
					id: 1,
					testStatus: 0, // 是否提交
					isSubmitFirst: false
				}
			}
		},
		onLoad(option) {
			this.isSubmit = option.isExist === 'false' ? false : true
			this.testId = option.id
			console.log("isSubmit", this.isSubmit)
		},
		onShow() {
			getCareeranchorTest().then(res => {
				this.$set(this.Data, 'rows', res.rows);
				this.$set(this.Data, 'total', res.total);
			})
			this.ResultMap = new Map();
			this.ResultMap.set("GM", 0)
			this.ResultMap.set("TF", 0)
			this.ResultMap.set("AU", 0)
			this.ResultMap.set("SE", 0)
			this.ResultMap.set("EC", 0)
			this.ResultMap.set("SV", 0)
			this.ResultMap.set("CH", 0)
			this.ResultMap.set("LS", 0)
			// 选择题对应的分数  this.ResultMap.set( data[0].type  ,  新分数)    计算分数
			// 获得时间戳	
			this.date = new Date();
			this.startingTime = this.date.getTime();
			this.startDate = this.date;
			// 转日期
			this.dateResult.startTime = this.formatDateTime(this.date);
		},
		methods: {
			fanhui() {
				uni.navigateBack({
					delta: 1
				});
			},
			//控制开关弹窗
			toggleQuestionList() {
				this.showAllQuestionsModal = !this.showAllQuestionsModal;
			},
			//在用户点击题号跳转
			jumpToQuestion(index) {
				this.id = index;
				this.p = index + 1;
				if (index === this.Data.total - 1) {
					this.text = "提交";
				} else {
					this.text = "下一题";
				}
				this.scrollToCurrent();
				this.showAllQuestionsModal = false
			},
			// 已答题数统计（用于提示剩余多少题）
			answeredCount() {
				return Object.keys(this.selectedOptions).length;
			},
			//查看有没有未答的题 并跳转到未答题的页面
			checkAllAnswered() {
				let totalQuestions = this.Data.total;
				for (let i = 0; i < totalQuestions; i++) {
					if (this.selectedOptions[i] === undefined) {
						return i; // 返回第一道未答题的索引
					}
				}
				return -1; // 全部已答
			},
			getTimeDifferenceStr(date1, date2) {
				const diffMs = Math.abs(date2 - date1); // 获取时间差（毫秒）
				const totalSeconds = Math.floor(diffMs / 1000);
				const hours = Math.floor(totalSeconds / 3600);
				const minutes = Math.floor((totalSeconds % 3600) / 60);
				const seconds = totalSeconds % 60;
				let result = '';
				if (hours > 0) result += `${hours}小时`;
				if (minutes > 0) result += `${minutes}分`;
				if (seconds > 0 || result === '') result += `${seconds}秒`; // 如果前面都为0，也显示秒
				return result;
			},
			formatDateTime(date) {
				const year = date.getFullYear();
				const month = (date.getMonth() + 1).toString().padStart(2, '0'); // 月份从0开始，需+1 
				const day = date.getDate().toString().padStart(2, '0');
				const hours = date.getHours().toString().padStart(2, '0');
				const minutes = date.getMinutes().toString().padStart(2, '0');
				return `${year}-${month}-${day} ${hours}:${minutes}`;
			},
			select(score) {

				const currentId = this.id;
				const currentType = this.Data.rows[currentId].category;

				// 获取当前题目的旧分数（如果答过）
				const oldScore = this.answerMap[currentId];
				// 如果答过，需要先减去旧分数
				if (oldScore !== undefined) {
					this.ResultMap.set(currentType, this.ResultMap.get(currentType) - oldScore);
				}
				// 设置新分数
				this.$set(this.selectedOptions, currentId, score);
				this.$set(this.answerMap, currentId, score);
				// 加上新分数
				this.ResultMap.set(currentType, this.ResultMap.get(currentType) + score);
				console.log(this.ResultMap);
				// 如果开启了自动跳转
				if (this.value) {
					// 延时跳转开始
					setTimeout(() => {
						this.unclick(1);
					}, 500); // 延时 300 毫秒（0.3秒）
				}
			},

			unclick(e) {
				if (this.id <= this.Data.total - 1) {
					if (e === 1) {
						this.id = this.id + 1
						if (this.id < this.Data.total) {
							this.p = this.p + 1
						}
						if (this.id == this.Data.total - 1) {
							this.text = "提交"
						}
						if (this.id == this.Data.total) {
							this.id = this.id - 1;
							this.date = new Date() // 获得结束日期
							this.endingTime = this.date.getTime();
							this.duringTime = this.endingTime - this.startingTime; // 用时多长
							console.log(this.duringTime);
							this.checkAndSubmit();
							return;
						}
					} else if (e === 2) {
						this.text = "下一题"
						this.id = this.id - 1
						this.p = this.p - 1
					}
				}
			},
			checkAndSubmit() {
				const firstUnanswered = this.checkAllAnswered();
				if (firstUnanswered !== -1) {
					uni.showModal({
						title: '提示',
						content: `还有 ${this.Data.total - this.answeredCount()} 题未答，是否继续提交？`,
						showCancel: true,
						confirmText: '继续提交',
						cancelText: '查看未答',
						success: (res) => {
							if (res.confirm) {
								this.submitAnswer();
							} else {
								this.id = firstUnanswered;
								this.p = firstUnanswered + 1;
								this.text = "下一题"
								this.scrollToCurrent(); // 新增：自动滚动到当前题号
							}
						}
					});
				} else {
					this.submitAnswer();
				}
			},
			combineLetter(array) {
				let str = ""
				for (let i = 0; i < array.length - 1; i += 2) {
					if (array[i][1] >= array[i + 1][1]) {
						str = str + array[i][0]
					} else {
						str = str + array[i + 1][0]
					}
				}
				return str
			},
			//提交答案代码
			submitAnswer() {
				// 获取当前时间，记录答题结束时间
				this.date = new Date();
				this.endingTime = this.date.getTime();
				// 计算答题总时长（单位：毫秒）
				this.duringTime = this.endingTime - this.startingTime;
				// 设置最短答题时间为 5 分钟（300000 毫秒）
				const MIN_DURATION = 3 * 60 * 1000;
				// 判断用户是否已答题至少 5 分钟
				// if (this.duringTime >= MIN_DURATION) {
				if (true) {
					// 计算并格式化答题时长（例如：5分30秒）
					this.dateResult.during = this.getTimeDifferenceStr(this.startDate, new Date());
					// 将结果映射表（ResultMap）转换为对象并赋值给 dateResult.type
					this.dateResult.type = Object.fromEntries(this.ResultMap);

					// 将每个维度的得分拼接为字符串，形如 "E:20 I:10 F:16 T:14 ..."
					const type = this.combineLetter(Object.entries(this.dateResult.type))
					
					// 构造面向 AI 问答的 prompt，让 AI 根据 MBTI 结果分析人格与职业建议
					let questionAi = "我通过职业锚测试后，" + type + "请问我是什么人格类型？有什么特定？适合什么职业？"

					// 跳转至测试结果展示页面，并通过 URL 参数传递测试数据、是否提交状态、AI 问题文本和测试 ID
					uni.redirectTo({
						url: "/pages/careerModel/careerResult/careerResult" +
							"?data=" + encodeURIComponent(JSON.stringify(this.dateResult)) + // 测试结果数据
							"&isSubmit=" + this.isSubmit + // 是否是提交状态
							"&questionAi=" + questionAi + // AI 问题 prompt
							"&testId=" + this.testId + // 当前测试的 ID
							"&type=" + type
					})
				} else {
					// 如果答题时长不足 5 分钟，计算还需要等待的分钟数（向上取整）
					const remainMinute = Math.ceil((MIN_DURATION - this.duringTime) / 60000);

					// 弹出提示，提醒用户继续答题
					uni.showToast({
						title: `答题时间不足3分钟，请在 ${remainMinute} 分钟后提交`,
						icon: 'none',
						duration: 3000
					});
				}
			},
		},
	}
</script>
<style>
	.big-box {
		width: 100%;
		min-height: 100vh;
		background-color: #f2f2f2;
		display: flex;
		flex-direction: column;
		align-items: center;
	}
	.box{
		width: 100%;
		height: 100%;
		margin-top: 30px;
	}
	.fanhui{
		width: 30px;
		height: 30px;
		cursor: pointer;
	}

	.box-header-all {
		display: flex;
		background-color: #fff;
		padding: 20px 30px;
		box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
		animation: facein 0.5s ease-out;
		width: 90%;
		height: 20px;
		/* Adjust width for better fit on tablet */
		max-width: 1200px;
		/* Limit max width */
		margin: 0 auto;
	}

	.question-nav-container {
		width: 100%;
		overflow: hidden;
		background-color: #f5f5f5;
		padding: 10rpx 0;
	}

	.question-nav-scroll {
		display: flex;
		flex-direction: row;
		overflow-x: auto;
		height: 80rpx;
		white-space: nowrap;
		scroll-behavior: smooth;
		/* 平滑滚动 */
	}

	.question-nav-list {
		display: flex;
		align-items: center;
		height: 100%;
	}

	.question-item {
		display: inline-flex;
		justify-content: center;
		align-items: center;
		width: 60px;
		/* 固定宽度 */
		height: 60px;
		margin: 0;
		/* 禁止外边距干扰 */
		line-height: 60px;
		text-align: center;
		border-radius: 50%;
		color: #fff;
		background-color: #aaa;
		font-size: 14px;
		flex-shrink: 0;
		z-index: 1;
	}

	.question-item.answered {
		background-color: #2979ff;
	}

	.question-item.current {
		background-color: #e63c3c;
		transform: scale(1.2);
		transition: transform 0.2s;
		z-index: 2;
	}

	.box-header {
		margin: 0 auto;
		font-size: 18px;
		font-weight: 700;
		color: #333;
		flex-grow: 1;
		/* Allow box-header to grow and fill available space */
		text-align: center;
		line-height: 20px;
		/* Center text within box-header */
	}

	.footer {
		display: flex;
		align-items: center;
		justify-content: flex-end;
		/* 可选：让内容靠右对齐 */
		padding-right: 15px;
		height: 10px;
	}

	.footer-content {
		padding-top: 10px;
		display: flex;
		align-items: center;
		gap: 8px;
		/* 可选：图标和文字之间的间距 */
	}

	.box2 {
		background-color: #ffffff;
		border-radius: 20px;
		margin: 30px;
		padding: 30px;
		box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
		animation: facein 0.5s ease-out;
		width: 90%;
		max-width: 1200px;
		/* 		height: 300px; */
	}

	.div2 {
		height: 10px;
		display: flex;
		justify-content: space-between;
		align-items: center;
		margin-bottom: 20px;
	}

	.question-progress {
		color: #9013bc;
		font-size: 25px;
		font-weight: 700;
	}

	.question-total {
		color: #999;
		font-size: 20px;
		font-weight: 500;
		margin-left: 6px;
	}

	.div3 {
		display: flex;
		align-items: center;
		gap: 10px;
	}

	.auto-next-text {
		font-size: 15px;
		color: #999;
	}

	.div4 {
		border-top: 2px solid #f2f2f2;
		padding-top: 30px;
	}

	.question-text {
		font-size: 16px;
		color: #333;
		font-weight: 600;
		margin-bottom: 20px;
	}

	.options-box {
		display: grid;
		grid-template-columns: repeat(2, 1fr);
		/* Two columns */
		gap: 20px;
	}

	.option-item1 {
		padding: 10px 30px;
		font-size: 13px;
		color: #333;
		border-bottom: 3px solid #f2f2f2;
		border-radius: 10px;
		transition: all 0.3s ease-in-out;
		cursor: pointer;
	}

	.option-item1.selected {
		background-color: #d7ebff !important;
		color: #169BD5 !important;
		font-weight: bold;
		border: 2px solid #169BD5 !important;
		transform: scale(1.02) !important;
	}

	.div6 {
		display: flex;
		align-items: center;
		color: #9013BC;
		margin-top: 20px;
		cursor: pointer;
	}

	.jiantou {
		width: 20px;
		height: 20px;
	}

	.prev-text {
		margin-left: 5px;
		font-size: 15px;
	}

	.btn-box {
		margin-top: 20px;
		display: flex;
		justify-content: center;
		align-items: center;
	}

	.button1 {
		width: 70%;
		height: 60rpx;
		line-height: 60rpx;
		background-color: #169BD5;
		color: white;
		font-size: 30rpx;
		border-radius: 50rpx;
		text-align: center;
		padding-bottom: 75rpx;
		transition: background-color 0.3s ease-in-out, transform 0.3s ease;
	}

	.button1:hover {
		transition: 0.5s ease-out;
		transform: scale(1.05);
	}

	.button2 {
		width: 20%;
		height: 60rpx;
		line-height: 60rpx;
		background-color: #169BD5;
		color: white;
		font-size: 30rpx;
		border-radius: 50rpx;
		text-align: center;
		padding-bottom: 75rpx;
		transition: background-color 0.3s ease-in-out, transform 0.3s ease;
	}

	.button2:hover {
		transition: 0.5s ease-out;
		transform: scale(1.05);
	}

	@keyframes facein {
		from {
			opacity: 0;
			transform: scale(0.9);
		}

		to {
			opacity: 1;
			transform: scale(1);
		}
	}

	.modal-overlay {
		pointer-events: auto;
		/* 确保父级也响应点击 */
		position: fixed;
		top: 0;
		left: 0;
		right: 0;
		bottom: 0;
		background-color: rgba(0, 0, 0, 0.5);
		display: flex;
		align-items: center;
		justify-content: center;
		z-index: 9999;
	}

	.modal-content {
		pointer-events: auto;
		/* 明确允许点击 */
		background-color: #fff;
		width: 80%;
		border-radius: 12px;
		padding: 20px;
		max-height: 60vh;
		overflow-y: auto;
		position: relative;
		z-index: 10000;
	}

	.question-list {
		display: flex;
		flex-wrap: wrap;
		gap: 10px;
		justify-content: center;
	}

	.question-number {
		-webkit-tap-highlight-color: transparent;
		/* 禁止高亮 */
		user-select: none;
		/* 禁止文字选择 */
		/* 加一个样式防止被拦截： */
		pointer-events: auto;
		width: 60rpx;
		height: 60rpx;
		display: flex;
		justify-content: center;
		align-items: center;
		border-radius: 50%;
		background-color: #aaa;
		color: white;
		font-size: 24rpx;
	}

	.question-number.answered {
		background-color: #2979ff;
	}

	.question-number.current {
		background-color: #e63c3c;
		transform: scale(1.2);
		transition: transform 0.2s;
	}

	.liebiao {
		width: 50px;
		height: 50px;
	}

	/* Responsive adjustments for smaller screens */
	@media (max-width: 768px) {

		.box-header-all,
		.box2 {
			width: 95%;
			padding: 10px 20px;
		}

		.box-header {
			font-size: 28px;
		}

		.button1 {
			width: 90%;
			height: 50px;
			line-height: 50px;
		}
	}
</style>